package com.fa.wisdom.net;


import com.fa.wisdom.model.ResultEntity;
import com.fa.wisdom.utils.SpUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class MyCallback<T> implements Callback<T> {
  private Response responseNet;
  @Override
  public void onResponse(Call call, Response response) {
    responseNet = response;
    switch (response.code()) {
      case 401:
        //清空用户信息
        SpUtils.getInstance().removeAllKey();
        onFailure(new Throwable("客户端token已过期，请重新登录~~"));
        break;
      case 500:
        onFailure(new Throwable("服务器出现错误，请稍后重试~"));
        break;
      case 200:
        verifyToken(response);
        break;
    }
  }

  @Override
  public void onFailure(Call call, Throwable t) {
    onFailure(t);
  }

  protected abstract void onSuccess(Response<T> response);


  protected abstract void onFailure(Throwable t);

  private void verifyToken(Response<ResultEntity> response) {
    int code = response.body().getCode();
    switch (code) {
      case 0:
        onSuccess(responseNet);
        break;
      case -1:
        onFailure(new Throwable(response.body().getMsg()));
        break;
    }
  }
}
